#! /usr/bin/env python
# -*- coding:utf-8 -*-
# Author:Teny

"""
自定义的分页组件，以后如果想要使用这个分页组件，你需要做如下几件事：

在视图函数中：
    def pretty_list(request):

        # 1.根据自己的情况去筛选自己的数据
        queryset = models.PrettyNum.objects.all()

        # 2.实例化分页对象
        page_object = Pagination(request, queryset)

        context = {
            "queryset": page_object.page_queryset,  # 分完页的数据
            "page_string": page_object.html()       # 生成页码
        }
        return render(request, 'pretty_list.html', context)

在HTML页面中

    {% for obj in queryset %}
        {{obj.xx}}
    {% endfor %}

    <ul class="pagination">
        {{ page_string }}
    </ul>

"""
from django.utils.safestring import mark_safe
from django.http.request import QueryDict
import copy

class Pagination(object):
    def __init__(self,request,queryset,page_size=10,plus=5,page_param="page"):
        """
        :param request: 请求的对象
        :param queryset: 符合条件的数据（根据这个数据给他进行分页处理）
        :param page_size: 每页显示多少条数据
        :param plus: 显示当前页的 前或后几页（页码）
        :param page_param: 在URL中传递的获取分页的参数，例如：/etty/list/?page=12
        """

        # 获取当前路径参数并深复制修改
        query_dict = copy.deepcopy(request.GET)
        query_dict._mutable = True
        self.query_dict = query_dict

        # 获取参数页码 ?page=1
        self.page_param = page_param
        page = request.GET.get(page_param, "1")
        if page.isdecimal():
            page = int(page)
        else:
            page = 1

        self.page = page
        self.page_size = page_size

        self.start_size = (page - 1) * page_size
        self.end_size = page * page_size
        # 分页后queryset
        self.page_queryset = queryset[self.start_size:self.end_size]

        # 总条数
        total_count = queryset.count()
        # 总页数
        page_count, div = divmod(total_count,page_size)
        if div != 0:
            page_count += 1
        self.page_count = page_count

        self.plus = plus

    def html(self):
        # 计算当前页的前五页，后五页
        # 极值处理
        if self.page_count <= 2 * self.plus + 1:
            page_start = 1
            page_end = self.page_count
        else:
            # 当前页小于 plus 时
            if self.page <= self.plus:
                page_start = 1
                page_end = 2 * self.plus + 1
            else:
                # 当前页超过总页码
                if (self.page + self.plus) > self.page_count:
                    page_start = self.page_count - 2 * self.plus
                    page_end = self.page_count
                else:
                    page_start = self.page - self.plus
                    page_end = self.page + self.plus

        # 页码
        page_list = []
        # 首页
        if self.page == 1:
            self.query_dict.setlist(self.page_param, [1])
            page_list.append('<li class="disabled"><a href="?{}">首页</a></li>'.format(self.query_dict.urlencode()))
        else:
            self.query_dict.setlist(self.page_param, [1])
            page_list.append('<li><a href="?{}">首页</a></li>'.format(self.query_dict.urlencode()))

        # 上一页
        if self.page == 1:
            self.query_dict.setlist(self.page_param, [1])
            page_list.append('<li class="disabled"><a href="?{}">上一页</a></li>'.format(self.query_dict.urlencode()))
        else:
            self.query_dict.setlist(self.page_param, [self.page - 1])
            page_list.append('<li><a href="?{}">上一页</a></li>'.format(self.query_dict.urlencode()))

        for i in range(page_start, page_end + 1):
            self.query_dict.setlist(self.page_param, [i])
            if i == self.page:
                page_list.append('<li class="active"><a href="?{}">{}</a></li>'.format(self.query_dict.urlencode(), i))
            else:
                page_list.append('<li><a href="?{}">{}</a></li>'.format(self.query_dict.urlencode(), i))
        # 下一页
        if self.page == self.page_count:
            self.query_dict.setlist(self.page_param, [self.page_count])
            page_list.append('<li class="disabled"><a href="?{}">下一页</a></li>'.format(self.query_dict.urlencode()))
        else:
            self.query_dict.setlist(self.page_param, [self.page + 1])
            page_list.append('<li><a href="?{}">下一页</a></li>'.format(self.query_dict.urlencode()))

        # 尾页
        if self.page == self.page_count:
            self.query_dict.setlist(self.page_param, [self.page_count])
            page_list.append('<li class="disabled"><a href="?{}">尾页</a></li>'.format(self.query_dict.urlencode()))
        else:
            self.query_dict.setlist(self.page_param, [self.page_count])
            page_list.append('<li><a href="?{}">尾页</a></li>'.format(self.query_dict.urlencode()))

        # 跳转
        search_str = """
        <li>
            <form method="get" style="float: left;">
                <input style="position: relative;float: left;display: inline-block;width: 88px" type="text" class="form-control" name="page" placeholder="页码">
                <button class="btn btn-default" type="submit">跳转</button>
            </form>
        </li> 
        """
        page_list.append(search_str)

        page_str = mark_safe(''.join(page_list))

        return page_str

